'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	//event为客户端上传的参数
	//客户端信息
	const dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云函数的event和context，必传
			event,
			context
		})
	let chapter = await dbJQL.collection('mydb-course-chapter').where('/Part B/.test(title) && /2000/.test(title)').field('title').get()
	
	let ids=chapter.data.map((item)=>item._id)
	let titles=chapter.data.map((item)=>item.title.split(" Part B")[0])
	console.log('ids : ', ids)
	console.log('titles : ', titles)
	let idmaps=''
	ids.forEach((item)=>{
		idmaps+=`'${item}',`
	})
	idmaps=idmaps.slice(0, -1);
	console.log('idmaps',idmaps)
	let words = await dbJQL.collection('mydb-course-unit').where(`chapter_id in [${idmaps}]`).field('word,chapter_id').get()
	
	words=words.data
	console.log('words.length : ', words.length)
	for (var i = 0; i < words.length; i++) {
		let chapter_id=words[i]['chapter_id']
		let chapter = await dbJQL.collection('mydb-course-chapter').where(`_id == '${chapter_id}'`).field('title').get()

		let title=chapter.data[0].title.split(" Part B")[0]
		let updateChapter = await dbJQL.collection('mydb-course-chapter').where(`title == '${title}'`).field('_id').get()
		console.log('updateChapter : ',chapter_id, updateChapter.data[0]['_id'])
		let update = await dbJQL.collection('mydb-course-unit').where({_id:words[i]['_id']}).update({
			chapter_id:updateChapter.data[0]['_id']
		})
		console.log('update : ',update)
	}
	//返回数据给客户端
	return event
};
